﻿using log4net;
using ServerControl.Dal;
using ServerControl.Model;
using ServerControl.Model.Enum;
using ServerControl.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ServerControl.WebManage.Attributes
{
    public class ApkAttribute : AuthorizeAttribute
    {
        private ILog logger = LogManager.GetLogger("ApkAttribute");
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isLogin = false;

            try
            {
                var request = httpContext.Request;
                Dictionary<string, string> dicts = new Dictionary<string, string>();
                request.Headers.AllKeys.ToList().ForEach(key => 
                {
                    dicts.Add(key.ToLower(), request.Headers[key]);
                });


                //var keys = new List<string>();
                //request.Headers.AllKeys.ToList().ForEach(key => { keys.Add(key.ToLower()); });

                if (dicts.Keys.Contains("username") && dicts.Keys.Contains("code"))
                {
                    var userName = dicts["username"];
                    var code = dicts["code"];
                    var user = UserDal.GetLoginUser(userName, code);
                    
                    if (user != null)
                    {
                        isLogin = true;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return isLogin;
            //return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult { Data = new { code = ResultCode.UnAuth, msg = "非法请求" } };
            }
            else
            {
                filterContext.Result = new JsonResult { Data = new { code = ResultCode.UnAuth, msg = "非法请求" } };
            }
        }
    }
}